#!/bin/bash 
# 设置命令标题名称
echo -ne "\e]2;银河麒麟V10Sp1工具箱\a"

# 确保脚本在终端中运行
if [ -z "$TERM" ]; then
    # 如果没有终端，尝试启动一个终端来运行脚本
    x-terminal-emulator -e "$0"
    exit 0
fi

# 颜色定义
red='\033[0;31m' 
green='\033[0;32m' 
yellow='\033[0;33m'
blue='\033[0;34m' 
cyan='\033[0;36m'
magenta='\033[0;35m' 
reset='\033[0m'
nc='\033[0m'

# 优化图标路径检查
icon_path="/usr/share/icons/hicolor/48x48/apps/xq-kylin-tools.png"
[[ ! -f "$icon_path" ]] && icon_path=""  # 图标不存在时不显示

# ====================== 通知工具函数 ======================
# 桌面通知与终端提示函数
show_notification() { 
    local title="$1" message="$2" level="$3" icon="${4:-}"
    case "$level" in
        "success") color="$green"; urgency="normal" ;;
        "warning") color="$yellow"; urgency="normal" ;;
        "error")   color="$red"; urgency="critical" ;;
        *)         color="$nc"; urgency="normal" ;;
    esac
    echo -e "\n${color}【$title】${message}${NC}"
    # 发送桌面通知
    if command -v notify-send &> /dev/null; then
        if [[ -n "$icon" && -f "$icon" ]]; then
            notify-send -u "$urgency" -i "$icon" "$title" "$message" 2>/dev/null || true
        else
            notify-send -u "$urgency" "$title" "$message" 2>/dev/null || true
        fi
    fi
}

# ====================== 权限检查与获取函数 ======================
# 错误处理函数 - 防止闪退并提示用户
handle_error() {
    local message="$1"
    echo -e "\n${red}【错误】${message}${NC}"
    show_notification "操作失败" "${message}" "error" "$icon_path"
    read -p "按Enter键继续或关闭窗口..."  # 防止闪退，等待用户确认
}
echo -e "${blue}▶ 正在验证sudo权限，请输入您的密码...${NC}"

if sudo -v; then
    echo -e "\n${green}【成功】sudo权限验证通过，继续执行后续操作${NC}"
else
    echo -e "\n${red}【错误】sudo权限验证失败！原因可能是：${NC}" 
    echo -e "${yellow}1. 当前用户未配置sudo权限"
    echo -e "2. 密码输入错误"
    exit 1
fi

# 用户确认函数：提示用户确认操作（y/n），返回 0（确认）或 1（取消）
confirm_operation() {
    echo -en "${yellow}$1 (y/n): ${reset}"
    read -r response
    [[ "$response" =~ ^[Yy]$ ]] && return 0 || return 1  
}


# ====================== 3）系统优化菜单开始 ======================
# 系统优化菜单：处理性能优化、磁盘清理、个性化
system_optimize_menu() {
    while true; do
        clear
        echo -e "${blue}======================  银河麒麟工具箱  =====================${reset}"        
        echo -e "${green}╔══════════════════════════════════════════════════════════╗"
        echo -e "║                           系统优化                       ║"
        echo -e "╚══════════════════════════════════════════════════════════╝${reset}"              
        echo -e " ${magenta}1)${reset} 系统性能优化"
        echo -e " ${magenta}2)${reset} 磁盘清理工具"
        echo -e " ${magenta}3)${reset} 个性化设置"
        echo -e " ${red}0)${reset} 返回主菜单"

        echo -e "${blue}$(printf '═%.0s' $(seq 1 60))${reset}"
        echo -en "${yellow}请输入选项编号 [ 例如：1 ]: ${reset}"
        read -rp "" choice
        case $choice in
            1) optimize_system_performance;   break ;;
            2) clean_disk_menu;   break ;;
            3) configure_personalization; break ;;
            0) echo -e "${green}→ 正在返回主菜单（银河麒麟V10Sp1）...${reset}";  break ;;
            *) echo -e "${red}✗ 无效选择，请重新输入！${reset}"; sleep 0.5 ;;
        esac
        echo -e "\n${yellow}按Enter键继续...${reset}"
        read -r
    done
}
# ====================== 系统性能优化子菜单 ======================
# 系统性能优化子菜单：多维度优化系统性能
optimize_system_performance() {
    while true; do
        clear
         echo -e "${blue}======================  银河麒麟工具箱  =====================${reset}"
        echo -e "${green}╔══════════════════════════════════════════════════════════╗"
        echo -e "║                         系统性能优化                     ║"
        echo -e "╚══════════════════════════════════════════════════════════╝${reset}"             
        echo -e "1) 关闭动画特效                      2) 优化内存使用"
        echo -e "3) 禁非必要服务                      4) 优化DNS设置"
        echo -e "5) 优化文件系统                      6) 修复高CPU占用"
        echo -e "7) 管理开机自启                      8) 关闭网络邻居列表"

        echo -e "a) 一键优化全部"
        echo -e "0) 返回上级菜单"
        echo -e "══════════════════════════════"
        read -rp "请选择操作: " choice
        case $choice in
            1)  # 关闭UI动画特效
                gsettings set org.ukui.windows enable-animations false
                echo -e "${green}✓ V10Sp1 UI动画特效已关闭（含面板+窗口动画）${reset}"
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            2)  # 优化内存使用
                if ! grep -q "vm.swappiness=5" /etc/sysctl.conf; then
                    echo 'vm.swappiness=5' | sudo tee -a /etc/sysctl.conf
                    # 新增V10Sp1 内存回收优化参数
                    echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf
                    sudo sysctl -p
                    echo -e "${green}✓ 内存使用优化完成${reset}"
                else
                    echo -e "${yellow}已是最优配置${reset}"
                fi
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            3)  # 禁用非必要服务（打印机/蓝牙）
                if confirm_operation "确定要禁用非必要服务吗？"; then
                    sudo systemctl disable --now cups bluetooth kylin-system-monitor-agent
                    echo -e "${green}✓ V10Sp1 非必要服务已禁用（cups + bluetooth + 监控代理）${reset}"
                fi
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            4)  # 调用DNS优化函数
                optimize_dns_resolution 
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            5)  # 优化文件系统（TRIM操作）
                sudo fstrim -av
                if ! sudo systemctl is-enabled fstrim.timer &> /dev/null; then
                    sudo systemctl enable --now fstrim.timer
                    echo -e "${green}✓ V10Sp1 文件系统优化完成（手动TRIM + 定时任务启用）${reset}"
                else
                    echo -e "${green}✓ V10Sp1 文件系统TRIM优化完成（定时任务已启用）${reset}"
                fi
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            6)  # 修复高CPU占用（终止imwheel进程）
                pids=$(pgrep -f "imwheel|kylin-clipboard-manager")
                if [ -n "$pids" ]; then
                    sudo kill -9 $pids
                    # 禁用V10Sp1 自启项（含新进程kylin-clipboard-manager）
                    sudo sed -i '/imwheel\|kylin-clipboard-manager/d' /etc/xdg/autostart/*.desktop
                    sudo sed -i '/imwheel\|kylin-clipboard-manager/d' ~/.config/autostart/*.desktop
                    echo -e "${green}✓ 已终止并禁用 高占用进程（imwheel + 剪贴板管理器）${reset}"
                else
                    echo -e "${yellow}未检测到 高CPU占用进程${reset}"
                fi
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            7)  # 开机自启管理（添加/移除/查看）
                echo -e "${cyan}>>> 开机自启管理${reset}"
                echo -e "1) 添加自启动\n2) 移除自启动\n3) 查看当前配置"
                read -rp "选择操作: " sub_choice
                case $sub_choice in
                    1)  # 添加自启动项
                        read -rp "程序名称: " app_name
                        read -rp "执行命令: " exec_cmd
                        desktop_file="${HOME}/.config/autostart/${app_name}.desktop"
                        cat > "$desktop_file" <<EOF
[Desktop Entry]
Type=Application
Name=$app_name
Exec=$exec_cmd
X-UKUI-Autostart-enabled=true
EOF
                        chmod +x "$desktop_file"
                        echo -e "${green}[通知] 已添加自启动项${reset}"
                        ;;
                    2)  # 移除自启动项（重命名为.disabled）
                        read -rp "程序名称: " app_name
                        read -rp "执行命令: " exec_cmd
                        desktop_file="/etc/xdg/autostart/${app_name}.desktop"
                        sudo cat > "$desktop_file" <<EOF
[Desktop Entry]
Type=Application
Name=$app_name
Exec=$exec_cmd
X-GNOME-Autostart-enabled=true
X-UKUI-Autostart-enabled=true
EOF
                        sudo chmod +x "$desktop_file"
                        echo -e "${green}[通知] V10Sp1 系统级自启动项已添加${reset}"
                        ;;
                    3)  # 移除自启动项（兼容V10Sp1 双路径）
                        echo -e "${yellow}1) 移除用户级自启动\n2) 移除系统级自启动（需sudo）${reset}"
                        read -rp "选择类型: " rm_type
                        if [ "$rm_type" -eq 1 ]; then
                            files=($(ls ~/.config/autostart/*.desktop 2>/dev/null))
                        else
                            files=($(sudo ls /etc/xdg/autostart/*.desktop 2>/dev/null))
                        fi
                        if [ ${#files[@]} -eq 0 ]; then
                            echo -e "${yellow}未检测到对应级别的自启动项${reset}"
                            break
                        fi
                        for i in "${!files[@]}"; do
                            echo "$((i+1))) $(basename "${files[$i]}")"
                        done
                        read -rp "选择要移除的项目: " rm_num
                        rm_file="${files[$((rm_num-1))]}"
                        [ "$rm_type" -eq 1 ] && mv "$rm_file" "$rm_file.disabled" || sudo mv "$rm_file" "$rm_file.disabled"
                        echo -e "${green}[通知] 自启动项已禁用${reset}"
                        ;;
                    4)  # 查看当前配置（显示V10Sp1 双路径自启项）
                        echo -e "${yellow}=== V10Sp1 用户级自启动项 ===${reset}"
                        grep -h "Name\|Exec" ~/.config/autostart/*.desktop 2>/dev/null || echo "无用户级自启动项"
                        echo -e "\n${yellow}=== V10Sp1 系统级自启动项 ===${reset}"
                        sudo grep -h "Name\|Exec" /etc/xdg/autostart/*.desktop 2>/dev/null || echo "无系统级自启动项"
                        ;;
                esac
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            8)  # 关闭网络邻居列表
                sudo  systemctl  stop  avahi-daemon.socket  avahi-daemon.service
                sudo  systemctl  disable  avahi-daemon.socket  avahi-daemon.service
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;                
            a)  # 一键优化全部：执行所有优化项
                if confirm_operation "确定要执行全面优化吗？"; then
                    gsettings set org.ukui.windows enable-animations false
                    echo 'vm.swappiness=5' | sudo tee -a /etc/sysctl.conf
                    sudo sysctl -p
                    sudo systemctl disable --now cups bluetooth kylin-system-monitor-agent
                    optimize_dns_resolution
                    sudo fstrim -av
                    #关闭网络邻居多太列表的问题
                    sudo  systemctl  stop  avahi-daemon.socket  avahi-daemon.service
                    sudo  systemctl  disable  avahi-daemon.socket  avahi-daemon.service
                    # 修复高CPU占用（imwheel）
                    pids=$(pgrep imwheel)
                    [ -n "$pids" ] && sudo kill -9 $pids
                    echo -e "${green}✓ 全面优化完成${reset}"
                fi
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            0)  # 返回上级菜单
                break 
                ;;
            *)  # 无效选择（缩短sleep至0.5）
                echo -e "${red}无效选择！${reset}" 
                sleep 0.5
                ;;
        esac
    done
}

# ====================== 磁盘清理工具子菜单 ======================
# 磁盘清理工具子菜单：多维度清理系统垃圾
clean_disk_menu() {
    while true; do
        clear
         echo -e "${blue}======================  银河麒麟工具箱  =====================${reset}"
        echo -e "${green}╔══════════════════════════════════════════════════════════╗"
        echo -e "║                         磁盘清理工具                     ║"
        echo -e "╚══════════════════════════════════════════════════════════╝${reset}"             
        echo -e "1) 清理系统日志 (保留7天)        2) 清理APT缓存"
        echo -e "3) 清理临时文件                  4) 清理用户缓存"
        echo -e "5) 清理浏览器缓存                6) 清理Snap缓存"
        echo -e "7) 清理所有项目                  8) 出厂备份删除(删除无法恢复)"

        echo -e "${red}0) 返回上级菜单${reset}"
        echo -e "══════════════════════════════"
        read -rp "请选择操作: " choice
        case $choice in
            1)  # 清理7天前系统日志
                if confirm_operation "确定要清理7天前的系统日志吗？"; then
                    sudo journalctl --vacuum-time=7d
                    echo -e "${green}[通知] 系统日志已清理${reset}"
                fi
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            2)  # 清理APT缓存
                if confirm_operation "确定要清理APT缓存吗？"; then
                    sudo apt clean
                    sudo rm -rfv /var/cache/kylin-system-updater/*
                    sudo rm -rfv /var/lib/dpkg/lock-frontend
                    sudo rm -rfv /var/lib/dpkg/lock
                    echo -e "${green}[通知] APT缓存已清理${reset}"
                fi
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            3)  # 清理临时文件
                if confirm_operation "确定要清理临时文件吗？"; then
                    sudo rm -rfv /tmp/*
                    echo -e "${green}[通知] 临时文件已清理${reset}"
                fi
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            4)  # 清理用户缓存
                if confirm_operation "确定要清理用户缓存吗？"; then
                    sudo rm -rfv ~/.cache/*
                    echo -e "${green}[通知] 用户缓存已清理${reset}"
                fi
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            5)  # 清理主流浏览器缓存
                if confirm_operation "确定要清理浏览器缓存吗？"; then
                    sudo rm -rfv ~/.cache/{browser360,qaxbrowser,mozilla,chrome,chromium,opera,edge}/*
                    echo -e "${green}[通知] 浏览器缓存已清理${reset}"
                fi
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            6)  # 清理Snap缓存
                if confirm_operation "确定要清理Snap缓存吗？"; then
                    sudo rm -rfv ~/snap/*/common/.cache/*
                    echo -e "${green}[通知] Snap缓存已清理${reset}"
                fi
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            7)  # 全面清理所有项目
                if confirm_operation "确定要执行全面清理吗？"; then
                    sudo journalctl --vacuum-time=7d
                    sudo apt clean
                    sudo rm -rfv /tmp/*
                    rm -rfv ~/.cache/*
                    rm -rfv ~/.cache/{browser360,qaxbrowser,mozilla,chrome,chromium,opera,edge}/*
                    sudo rm -rfv ~/snap/*/common/.cache/*
                    sudo rm -rfv /var/cache/kylin-system-updater/*
                    sudo rm -rfv /var/lib/dpkg/lock-frontend
                    sudo rm -rfv /var/lib/dpkg/lock                    
                    echo -e "${green}[通知] 全面清理完成${reset}"
                fi
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            8)  # 删除出厂备份（不可恢复）
                if confirm_operation "确定要删除出厂备份吗？此操作不可恢复！"; then
                    sudo rm -rfv /recovery
                    echo -e "${green}[通知] 出厂备份已删除${reset}"
                fi
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            0)  # 返回上级菜单
                break 
                ;;
            *)  # 无效选择
                echo -e "${red}无效选择！${reset}" 
                sleep 0.5
                ;;
        esac
    done
}
# ====================== 个性化设置子菜单 ======================
# 个性化设置：自定义桌面/锁屏/屏保壁纸及文字
configure_personalization() {
    echo -e "${cyan}>>> 个性化设置 (桌面/锁屏/屏保)${reset}"
    read -rp "请输入用户名: " username
    # 验证用户存在性
    if ! id "$username" &>/dev/null; then
        echo -e "${red}✗ 用户 $username 不存在！${reset}"
        return 1
    fi
    # 创建个性化图片目录
    pic_dir="/home/$username/Pictures/SystemPictures"
    mkdir -p "$pic_dir"/{backgrounds,lockdown,restscreen}
    # 桌面壁纸设置
    if confirm_operation "设置自定义桌面壁纸？"; then
        echo -e "${yellow}请将壁纸文件放在 $pic_dir/backgrounds/ 目录下${reset}"
        gsettings set org.mate.background picture-filename "$pic_dir/backgrounds/default.jpg"
    fi
    # 锁屏壁纸设置
    if confirm_operation "设置自定义锁屏壁纸？"; then
        echo -e "${yellow}请将锁屏壁纸放在 $pic_dir/lockdown/ 目录下${reset}"
        gsettings set org.ukui.screensaver background "$pic_dir/lockdown/default.jpg"
    fi
    # 屏保文字设置
    if confirm_operation "配置屏保显示文字？"; then
        read -rp "输入屏保显示文字: " motto
        gsettings set org.ukui.screensaver-default mytext "$motto"
        gsettings set org.ukui.screensaver-default background background-path "$pic_dir/restscreen"
    fi
    echo -e "${green}[通知] 个性化设置完成${reset}"
    return 0 
}

# 执行主函数 
system_optimize_menu

# 添加循环保护，防止意外退出
if [ $? -ne 0 ]; then
    echo -e "${red}菜单执行出错，3秒后返回主菜单...${reset}"
    sleep 3
fi
